package cn.meizhu.user.controller;

import cn.meizhu.base.exception.Exceptions;
import cn.meizhu.user.domain.LoginInfo;
import cn.meizhu.user.domain.tro.UserDto;
import cn.meizhu.user.service.ILoginInfoService;
import cn.meizhu.user.service.IUserService;
import cn.meizhu.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class AccountController  {

    @Autowired
    private IUserService userService;

    @Autowired
    private ILoginInfoService loginInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/register")
    public AjaxResult register(@RequestBody UserDto userDto){
        try {
            userService.register(userDto);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }


    @PostMapping("/login")
    private AjaxResult login(@RequestBody UserDto userDto) {

        System.out.println(userDto);
        try {
            //返回的登录用户
            LoginInfo loginInfo = loginInfoService.login(userDto);
            //生成token
            String token = UUID.randomUUID().toString();
            //放入redis   30分钟后过期
            redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);
            //返回token和loginInfo给前端
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            //清空密码
            loginInfo.setPassword("");
            loginInfo.setSalt("");
            map.put("loginInfo",loginInfo);
            return AjaxResult.me().setResultObj(map);
        } catch (Exceptions exceptions) {
            exceptions.printStackTrace();
            return AjaxResult.me().setMessage(exceptions.getMessage());
        }
    }



}
